package abrindoojogo.exemplos.gameloop;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
import javax.swing.WindowConstants;

public class JogoLoopSimples extends JFrame implements KeyListener
{
    BufferStrategy bs;
    Contador contador;
    int nave_x, nave_y, nave_qtd;

    public JogoLoopSimples()
    {
	setUndecorated(true);
	setSize(800, 600);
	Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
	setLocation(d.width / 2 - 400, d.height / 2 - 300);
	setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
	setIgnoreRepaint(true);
	addKeyListener(this);
	contador = new Contador();
    }

    public void gameloop()
    {
	initialize();
	while (true)
	{
	    Thread.yield();
	    update();
	    render();
	}
    }

    public void initialize()
    {
	setVisible(true);
	createBufferStrategy(2);
	bs = getBufferStrategy();

	nave_x = 400;
	nave_y = 50;
	nave_qtd = 1;

	contador.inicia();
    }

    public void update()
    {
	contador.contaPulso();
	nave_x += 1;
	if (nave_x > getWidth() + 30)
	{
	    nave_x = 0;
	}
    }

    public void render()
    {
	contador.contaFrame();
	Graphics2D g = (Graphics2D) bs.getDrawGraphics();
	g.setColor(Color.black);
	g.fillRect(0, 0, getWidth(), getHeight());
	int x = nave_x;
	int y = nave_y;
	for (int i = 0; i < nave_qtd; i++)
	{
	    g.setColor(Color.yellow);
	    g.drawLine(x, y, x - 20, y - 5);
	    g.drawLine(x, y, x - 20, y + 5);
	    g.drawLine(x - 20, y - 5, x - 20, y + 5);
	    y += 15;
	    if (y > 550)
	    {
		y = nave_y;
		x += 15;
	    }
	}
	g.setColor(Color.white);
	g.drawString("Pulsos: " + contador.getPulsosPorSegundo() + "  Frames: " + contador.getFramesPorSegundo() + "          naves: " + nave_qtd, 10, 20);
	g.dispose();
	bs.show();
    }

    public void keyPressed(KeyEvent e)
    {
	if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
	{
	    System.out.println("Pulsos: " + contador.getPulsosPorSegundo() + "  Frames: " + contador.getFramesPorSegundo() + "          naves: " + nave_qtd);
	    System.exit(0);
	}

	if (e.getKeyCode() == KeyEvent.VK_UP)
	{
	    nave_y -= 1;
	}
	if (e.getKeyCode() == KeyEvent.VK_DOWN)
	{
	    nave_y += 1;
	}
	if (e.getKeyCode() == KeyEvent.VK_RIGHT)
	{
	    if (nave_qtd < 1054)
	    {
		nave_qtd += 1;
	    }
	}
	if (e.getKeyCode() == KeyEvent.VK_LEFT)
	{
	    if (nave_qtd > 1)
	    {
		nave_qtd -= 1;
	    }
	}
    }

    public void keyReleased(KeyEvent e)
    {
    }

    public void keyTyped(KeyEvent e)
    {
    }
}
